export default {
  mounted() {
    // window.addEventListener("scroll", this.handleScroll, true);
  },
  methods: {
    //初始化倒计时数据
    initCountDown(type, arr) {
      let timer = setInterval(() => {
        if (type == 'system') {
          this.formatCountDown(type, arr)
        } else {
          this.shopList.forEach((item, index) => {
            this.formatCountDown(type, JSON.parse(item.businessHours), index)

            // this.fixedPriceToDiscount用来判断非企业订单的组件引用了该minix。企业订单无限时优惠。
            // 开启了限时优惠。
            if (this.fixedPriceToDiscount && item.isDiscountEnable && false) {
              let disArr = [{ startTime: item.discountStartTime, endTime: item.discountEndTime }]
              this.formatCountDown('discount', disArr, index)
            }
          })
        }
      }, 1000)
      this.timerList.push(timer)
      this.countInfo.timer = timer
    },
    //格式化倒计时数据
    formatCountDown(type, arr, index) {
      let nowDate = new Date()
      let year = nowDate.getFullYear()
      let month = nowDate.getMonth() + 1
      let day = nowDate.getDate()
      let hour = nowDate.getHours()
      let minute = nowDate.getMinutes()
      let secound = nowDate.getSeconds()
      let nowTemp = nowDate.getTime()
      let dateWithFront = `${year}/${month}/${day}`

      let startTime = '',
        endTime = ''

      for (let i = 0; i < arr.length; i++) {
        let item = arr[i]
        if (item.startTime && item.endTime) {
          item.startTimeTemp = new Date(dateWithFront + ' ' + item.startTime).getTime()
          item.endTimeTemp = new Date(dateWithFront + ' ' + item.endTime).getTime()
          if (item.startTimeTemp > item.endTimeTemp) {
            if (nowTemp < item.startTimeTemp) {
              item.startTimeTemp = parseInt(item.endTimeTemp) - 1000 * 60 * 60 * 24
            } else if (nowTemp > item.endTimeTemp) {
              item.endTimeTemp = parseInt(item.endTimeTemp) + 1000 * 60 * 60 * 24
            }
            startTime = item.startTimeTemp
            endTime = item.endTimeTemp
          }
          if (nowTemp > item.startTimeTemp && nowTemp < item.endTimeTemp) {
            startTime = item.startTimeTemp
            endTime = item.endTimeTemp
            break
          } else {
            startTime = ''
            endTime = ''
          }
        }
      }

      if (startTime && endTime) {
        this.startCountDown(type, startTime, endTime, index)
        if (type == 'discount') {
          this.fixedPriceToDiscount(index)
        }
      } else {
        if (type == 'discount') {
          let isOutDiscount = !endTime || endTime - new Date().getTime() <= 0
          if (isOutDiscount) {
            this.fixedPriceToOriginalPrice(index)
          }
        }
      }
    },
    //执行数据递减
    startCountDown(type, startTimeStemp, endTimeStemp, index) {
      let nowDateStemp = new Date().getTime()
      let oneDayStemp = 1000 * 60 * 60 * 24
      let oneHourStemp = 1000 * 60 * 60
      let oneMinuteStemp = 1000 * 60
      let surplusStemp = endTimeStemp - nowDateStemp

      let day = parseInt(surplusStemp / oneDayStemp)
      let hour = parseInt((surplusStemp % oneDayStemp) / oneHourStemp)
      let minute = parseInt(((surplusStemp % oneDayStemp) % oneHourStemp) / oneMinuteStemp)
      let secound = parseInt((((surplusStemp % oneDayStemp) % oneHourStemp) % oneMinuteStemp) / 1000)

      if (hour <= 9) {
        hour = '0' + hour
      }
      if (minute <= 9) {
        minute = '0' + minute
      }
      if (secound <= 9) {
        secound = '0' + secound
      }

      if (type == 'system') {
        this.countInfo.systemHour1 = Number(String(hour).split('')[0])
        this.countInfo.systemHour2 = Number(String(hour).split('')[1])
        this.countInfo.systemMinute1 = Number(String(minute).split('')[0])
        this.countInfo.systemMinute2 = Number(String(minute).split('')[1])
        this.countInfo.systemSecound1 = Number(String(secound).split('')[0])
        this.countInfo.systemSecound2 = Number(String(secound).split('')[1])
      } else if (type == 'discount') {
        this.countInfo[`d_day${index}`] = day
        this.countInfo[`d_hour${index}`] = hour
        this.countInfo[`d_minute${index}`] = minute
        this.countInfo[`d_secound${index}`] = secound
      } else {
        this.countInfo[`day${index}`] = day
        this.countInfo[`hour${index}`] = hour
        this.countInfo[`minute${index}`] = minute
        this.countInfo[`secound${index}`] = secound
      }
    },
    /**
     * 倒计时: 根据营业时间段和当前时间 剩余时间（秒数）
     * 配合 u-count-down 组件使用
     * @param {array|string} HMS
     * @returns {number}
     */
    countDownS(HMS, type) {
      const HMSArr = Array.isArray(HMS) ? HMS : JSON.parse(HMS ?? '[]')
	  console.log('HMSArr',HMSArr,'type',type);
      if (HMSArr.length) {
        console.log('[HMSArr] :', HMSArr)
        const nowDate = new Date()
        const year = nowDate.getFullYear()
        const month = nowDate.getMonth() + 1
        const day = nowDate.getDate()
        const nowTamp = nowDate.getTime()
        const today = `${year}/${month}/${day}`
        const oneDayTamp = 24 * 3600 * 1000
        const tampArr = HMSArr.map(({ startTime, endTime }) => {
          const startTamp = startTime ? new Date(`${today} ${startTime}`.trim()).getTime() : null
          const endTamp = endTime ? new Date(`${today} ${endTime}`.trim()).getTime() : null
          return startTamp <= endTamp
            ? { startTamp, endTamp }
            : {
                startTamp: nowTamp < endTamp ? startTamp - oneDayTamp : startTamp,
                endTamp: nowTamp > startTamp ? endTamp + oneDayTamp : endTamp,
              }
        })
		console.log('tampArr',tampArr);

        // console.log('2024-8-1 12:00 ->', new Date('2024-8-1 12:00').getTime())
        // console.log('2024-8-1 12:00:59 ->', new Date('2024-8-1 12:00:59').getTime())
        // console.log('2024-08-01 12:00 ->', new Date('2024-08-01 12:00').getTime())
        // console.log('2024-08-01 12:00:59 ->', new Date('2024-08-01 12:00:59').getTime())
        // console.log('2024/8/1 12:00 ->', new Date('2024/8/1 12:00').getTime())
        // console.log('2024/8/1 12:00:59 ->', new Date('2024/8/1 12:00:59').getTime())
        // console.log('2024/08/01 12:00 ->', new Date('2024/08/01 12:00').getTime())
        // console.log('2024/08/01 12:00:59 ->', new Date('2024/08/01 12:00:59').getTime())

        const { endTamp } = tampArr.find(_ => _.startTamp <= nowTamp && nowTamp < _.endTamp) ?? {} // 符合当前时间段的营业范围
		console.log('???????????')
        if (endTamp) {
          const remainTotalS = (endTamp - nowTamp) / 1000
          const remainH = Math.floor(remainTotalS / 3600)
          const remainM = Math.floor((remainTotalS % 3600) / 60)
          const remainS = remainTotalS % 60
		  console.log(type === 'uni' ? { hour: remainH, minute: remainM, second: remainS } : remainTotalS);
          return type === 'uni' ? { hour: remainH, minute: remainM, second: remainS } : remainTotalS
        } else {
          return null
        }
      } else {
        return null
      }
    },
    businessRange(HMS) {
      const HMSArr = Array.isArray(HMS) ? HMS : JSON.parse(HMS ?? '[]')
      const range = HMSArr.find(_ => _.startTime && _.endTime)
      return range ? Object.values(range).join('~') : ''
    },
    //浮点数精度问题的解决方式
    //加法
    accAdd(arg1, arg2) {
      var r1, r2, m, c
      try {
        r1 = arg1.toString().split('.')[1].length
      } catch (e) {
        r1 = 0
      }
      try {
        r2 = arg2.toString().split('.')[1].length
      } catch (e) {
        r2 = 0
      }
      c = Math.abs(r1 - r2)
      m = Math.pow(10, Math.max(r1, r2))
      if (c > 0) {
        var cm = Math.pow(10, c)
        if (r1 > r2) {
          arg1 = Number(arg1.toString().replace('.', ''))
          arg2 = Number(arg2.toString().replace('.', '')) * cm
        } else {
          arg1 = Number(arg1.toString().replace('.', '')) * cm
          arg2 = Number(arg2.toString().replace('.', ''))
        }
      } else {
        arg1 = Number(arg1.toString().replace('.', ''))
        arg2 = Number(arg2.toString().replace('.', ''))
      }
      return (arg1 + arg2) / m
    },
    //减法
    accSub(arg1, arg2) {
      var r1, r2, m, n
      try {
        r1 = arg1.toString().split('.')[1].length
      } catch (e) {
        r1 = 0
      }
      try {
        r2 = arg2.toString().split('.')[1].length
      } catch (e) {
        r2 = 0
      }
      m = Math.pow(10, Math.max(r1, r2)) //last modify by deeka //动态控制精度长度
      n = r1 >= r2 ? r1 : r2
      return ((arg1 * m - arg2 * m) / m).toFixed(n)
    },
    //乘法
    accMul(arg1, arg2) {
      console.log('arg1', arg1)
      console.log('arg2', arg2)
      var m = 0,
        s1 = arg1.toString(),
        s2 = arg2.toString()
      try {
        m += s1.split('.')[1].length
      } catch (e) {}
      try {
        m += s2.split('.')[1].length
      } catch (e) {}
      return (Number(s1.replace('.', '')) * Number(s2.replace('.', ''))) / Math.pow(10, m)
    },
    //除法
    accDiv(arg1, arg2) {
      var t1 = 0,
        t2 = 0,
        r1,
        r2
      try {
        t1 = arg1.toString().split('.')[1].length
      } catch (e) {}
      try {
        t2 = arg2.toString().split('.')[1].length
      } catch (e) {}
      r1 = Number(arg1.toString().replace('.', ''))
      r2 = Number(arg2.toString().replace('.', ''))
      return (r1 / r2) * Math.pow(10, t2 - t1)
    },
    //h5触底加载
    handleScroll() {
      let scrollTop = document.documentElement.scrollTop //滚动高度
      let clientHeight = document.documentElement.clientHeight //可视高度
      let scrollHeight = document.documentElement.scrollHeight //内容高度
      if (scrollHeight - scrollTop === clientHeight) {
        //触底加载
      }
    },

    setHidden() {
      document.body.style.overflow = 'hidden'
    },
    setAuto() {
      document.body.style = ''
    },
  },
}
